package com.xlf.service.ai.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xlf.common.core.exception.BizException;
import com.xlf.common.redis.service.RedisCache;
import com.xlf.service.ai.config.OpenAiConfig;
import com.xlf.service.ai.constant.ModelConstant;
import com.xlf.service.ai.service.BaseClient;
import com.xlf.service.ai.service.MessagesContainer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Deque;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @Author xlf 2734029211@qq.com
 * @Date 2024/1/29 22:54
 * @Description: TODO
 * @Version 1.0
 */
@Service
@Slf4j
public class ErnieBot4Client extends BaseClient {


    private static final String TAG = "ErnieBot4Client";

    private static final String URL = ModelConstant.ERNIE_BOT_4_URL;

    private static final String accessTokenKey = "ai:accessToken";

    @Autowired
    OpenAiConfig openAiConfig;

    @Autowired
    RedisCache redisCache;

    /**
     * 设置持久化消息容器缓存多播消息
     * @param messagesContainer
     */
    @Autowired
    @Override
    public void setMessagesContainer(MessagesContainer messagesContainer) {
        super.setMessagesContainer(messagesContainer);
    }

    @Override
    public String getCustomAccessToken() {

        return redisCache.queryWithMutexAndBuild(accessTokenKey, key -> redisCache.getCacheObject(key), key -> {
            String token = getToken();
            redisCache.setCacheObject(key,token,29,DAYS);
            return token;
        });
    }

    @Override
    public String getURL() {
        return URL;
    }

    @Override
    public String getTag() {
        return TAG;
    }


    private String getToken(){

        log.info("尝试获取token");
        String body = HttpRequest.post("https://aip.baidubce.com/oauth/2.0/token?" +
                        "client_id=" + openAiConfig.getApiKey() +
                        "&client_secret=" + openAiConfig.getSecretKey() +
                        "&grant_type=client_credentials")
                .header("Content-Type", "application/json")
                .execute()
                .body();
        JSONObject jsonObject = JSONUtil.parseObj(body);

        String error = jsonObject.getStr("error");

        if(error != null)
            throw new BizException("access_token获取异常：" + error);

        String access_token = jsonObject.getStr("access_token");

        log.info("获取token成功,token:" + access_token);

        return access_token;
    }
}
